import { isEmpty } from "@cbd/utils";
import { getUuid } from '../../../utils/comm';
// 详情数据返回显示格式调整
const detailFormat = (datailData) => {
  const fields = datailData.map((ele, index) => {
    const { options = [], type } = ele;
    let { defaultValue } = ele;
    if (options && !isEmpty(options)) {
      let newDefaultValue = '';
      if (type === 'boolean' && defaultValue.split && defaultValue.split(',').length > 0) {
        newDefaultValue = [];
        defaultValue = defaultValue.split(',');
      }
      const newOption = options.map(oitem => {
        const key = getUuid();
        oitem.key = key;
        if (type === 'boolean' && defaultValue instanceof Array) {
          if (defaultValue.some(vitem => vitem === oitem.id)) {
            newDefaultValue.push(key);
          }
        } else if (defaultValue === oitem.id) {
          newDefaultValue = key;
        }
        return oitem;
      });
      ele.defaultValue = newDefaultValue;
      ele.options = newOption;
      ele.originalIndex = index;
    }
    return ele;
  });
  return fields;
}

// 保存数据格式调整
const fieldsFormat = (items = []) => {
  const fields = items.map(ele => {
    const { options, defaultValue, type } = ele;
    delete ele.icon;
    delete ele.originalIndex;
    delete ele.hidden;
    if (options && !isEmpty(options)) {
      let newDefaultValue = '';
      if (type === 'boolean' && defaultValue instanceof Array) {
        newDefaultValue = [];
      }
      options.map(oitem => {
        if (type === 'boolean' && defaultValue instanceof Array) {
          if (defaultValue.some(vitem => vitem === oitem.key)) {
            newDefaultValue.push(oitem.id);
          }
        } else if (defaultValue === oitem.key) {
          newDefaultValue = oitem.id;
        }
        delete oitem.key;
        return oitem;
      });
      if (type === 'boolean' && defaultValue instanceof Array) {
        ele.defaultValue = newDefaultValue.join(',');
      } else if (newDefaultValue) {
        ele.defaultValue = newDefaultValue;
      }
    }
    return ele;
  });
  return fields;
}

export {
  fieldsFormat,
  detailFormat,
}